package reduce.fz.com.reduce.photo;

import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;


import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;

import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.activity.BaseToolBarActivity;
import reduce.fz.com.reduce.adapter.PhotoAlbumAdapter;
import reduce.fz.com.reduce.bean.PhotoAlbumLVItem;
import reduce.fz.com.reduce.util.ReduceLog;
import reduce.fz.com.reduce.util.SDUtil;
import reduce.fz.com.reduce.util.Utils;


/**
 * 相册列表，包含最近相册
 */
public class PhotoAlbumActivity extends BaseToolBarActivity {
    private TextView mTitleView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photo_album);
        //设置中间标题
        mTitleView = new TextView(this);
        mTitleView.setText(R.string.select_album);
        mTitleView.setTextColor(getResources().getColor(R.color.white));
        //设定布局的各种参数
        Toolbar.LayoutParams params = new Toolbar.LayoutParams(
                Toolbar.LayoutParams.WRAP_CONTENT,
                Toolbar.LayoutParams.WRAP_CONTENT,
                Gravity.CENTER);
        params.setMargins(3, 3, 3, 4);//设置外边界
        mTitleView.setLayoutParams(params);
        mToolbar.addView(mTitleView);

        if (!SDUtil.ifExitsSD()) {
            Utils.showToast(this, R.string.sd_not_found);
            return;
        }

        Intent t = getIntent();
        if (!t.hasExtra("latest_count")) {//没有最新的信息就不处理
            return;
        }

        ListView listView = (ListView) findViewById(R.id.select_img_listView);

        final ArrayList<PhotoAlbumLVItem> list = new ArrayList<PhotoAlbumLVItem>();
        //“最近照片”
        list.add(new PhotoAlbumLVItem(getResources().getString(R.string.latest_image),
                t.getIntExtra("latest_count", -1), t.getStringExtra("latest_first_img")));
        //相册
        list.addAll(getImagePathsByContentProvider());

        PhotoAlbumAdapter adapter = new PhotoAlbumAdapter(this, list);
        listView.setAdapter(adapter);

        /**
         * 点击某个相册列表
         */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(PhotoAlbumActivity.this, PhotoWallActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                if (position == 0) { //第一行为“最近照片”
                    intent.putExtra("code", PhotoWallActivity.KEY_LATEST_ALBUM);
                } else { //某个文件夹的图片列表
                    intent.putExtra("code", PhotoWallActivity.KEY_FOLDER_ALBUM);
                    intent.putExtra("folderPath", list.get(position).pathName);
                }

                startActivity(intent);
                overridePendingTransition(R.anim.in_from_top, R.anim.out_from_bottom);
            }
        });

    }

    /**
     * 完成按钮菜单
     *
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_cancel, menu);
        return true;
    }

    /**
     * 点击完成按钮
     *
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_cancel) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void initWidget() {

    }

    @Override
    public void initListener() {

    }

    /**
     * 获取目录中图片的个数。
     */
    private int getImageCount(File folder) {
        if (folder == null) {
            return 0;
        }
        int count = 0;
        try {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (Utils.isImage(file.getName())) {
                        count++;
                    }
                }
            }
        } catch (Throwable e) {
            ReduceLog.e(e);
        }
        return count;
    }

    /**
     * 获取目录中最新的一张图片的绝对路径。
     */
    private String getFirstImagePath(File folder) {
        File[] files = folder.listFiles();
        if (files == null) {
            return null;
        }
        for (int i = files.length - 1; i >= 0; i--) {
            File file = files[i];
            if (Utils.isImage(file.getName())) {
                return file.getAbsolutePath();
            }
        }
        return null;
    }

    /**
     * 使用ContentProvider读取SD卡所有图片。
     */
    private ArrayList<PhotoAlbumLVItem> getImagePathsByContentProvider() {
        Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;

        String key_MIME_TYPE = MediaStore.Images.Media.MIME_TYPE;
        String key_DATA = MediaStore.Images.Media.DATA;

        ContentResolver mContentResolver = getContentResolver();

        // 只查询jpg和png的图片
        Cursor cursor = mContentResolver.query(mImageUri, new String[]{key_DATA},
                key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=? or " + key_MIME_TYPE + "=?",
                new String[]{"image/jpg", "image/jpeg", "image/png"},
                MediaStore.Images.Media.DATE_MODIFIED);

        ArrayList<PhotoAlbumLVItem> list = null;
        if (cursor != null) {
            if (cursor.moveToLast()) {
                //路径缓存，防止多次扫描同一目录
                HashSet<String> cachePath = new HashSet<String>();
                list = new ArrayList<PhotoAlbumLVItem>();

                while (true) {
                    try {
                        // 获取图片的路径
                        String imagePath = cursor.getString(0);

                        File parentFile = new File(imagePath).getParentFile();
                        if (parentFile != null) {
                            String parentPath = parentFile.getAbsolutePath();

                            //不扫描重复路径
                            if (!cachePath.contains(parentPath)) {
                                list.add(new PhotoAlbumLVItem(parentPath, getImageCount(parentFile),
                                        getFirstImagePath(parentFile)));
                                cachePath.add(parentPath);
                            }
                        }
                    } catch (Exception e) {
                        ReduceLog.e(e);
                    }
                    if (!cursor.moveToPrevious()) {
                        break;
                    }
                }
            }

            cursor.close();
        }

        return list;
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        //动画
        overridePendingTransition(R.anim.in_from_bottom, R.anim.out_from_top);
    }


}
